# DEPENDEBCIES
lappend auto_path d:/codes/tcl/tank/lib

# PACKAGE
package provide anonymous 0.1

#

# Main
namespace eval anonymous {
    namespace export @ ~

    proc restoreSymbol {body} {
        foreach s1 {( ) &} s2 {[ ] $} {
            set regx "(\[^\\\\\]?)\\$s1"
            regsub -all $regx $body "\\1$s2" body
        }
        return $body
    }

    proc varsHead {body} {
        array set contextVars {}
        foreach w [regexp -all -inline {\$[:\w]+|\$\{[:\w]+\}} $body] {
            set w [string trimleft [string trimright $w \}] \$\{]
            set contextVars($w) {}
        }
        set varsHead {}
        foreach v [array names contextVars] {
            if [uplevel info exists $v] {
                upvar $v var
                append varsHead [list set $v $var]\n
            }
        }
        return $varsHead
    }

    proc @ {vars body} {
        set body [varsHead $body][uplevel [list subst -novariables $body]]
        return [list $vars [uplevel subst [list $body]]]
    }

    proc ~ {anonymous args} {
        foreach {vars body} $anonymous {}
        set head {}
        foreach var $vars val $args {
            append head "set $var $val\n"
        }
        return [eval "$head [restoreSymbol $body]"]
    }
}


